﻿using JWTAuthentication.Helper.JsonConverter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace JWTAuthentication.Helper {
    /// <summary>
    /// Json帮组类，使用System.Text.Json
    /// </summary>
    public class JsonHelper {
        /// <summary>
        /// 序列化json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize(object obj) {
            var jsonOptions = new JsonSerializerOptions {
                //美化JSON
                WriteIndented = true,
                //格式策略，目前内置的仅有一种策略CamelCase
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            //添加事件格式化类
            jsonOptions.Converters.Add(new JWTAuthentication.Helper.JsonConverter.DateTimeConverter());
            jsonOptions.Converters.Add(new DateTimeNullConverter());
            return JsonSerializer.Serialize(obj, jsonOptions);
        }

        /// <summary>
        /// 反序列成json对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string jsonStr) {
            return JsonSerializer.Deserialize<T>(jsonStr);
        }
    }
}
